package com.smile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.mapper.LoginLogMapper;
import com.smile.model.domain.SmilePlusLoginLog;
import com.smile.model.dto.request.AddLoginLogRequestDTO;
import com.smile.model.dto.request.GetLoginLogListRequestDTO;
import com.smile.model.response.response.GetLoginLogListResponseDTO;
import com.smile.service.LoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class LoginLogServiceImpl implements LoginLogService {
    @Autowired
    private LoginLogMapper loginLogMapper;

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public Boolean addLoginLog(AddLoginLogRequestDTO addLoginLogRequestDTO) {
        SmilePlusLoginLog smilePlusLoginLog = new SmilePlusLoginLog();
        smilePlusLoginLog.setCreateTime(LocalDateTime.now());
        BeanUtil.copyProperties(addLoginLogRequestDTO, smilePlusLoginLog);
        smilePlusLoginLog.setCreateTime(LocalDateTime.now());
        try{

        loginLogMapper.insert(smilePlusLoginLog);
        }catch (Exception e){
            e.printStackTrace();
        }
        return Boolean.TRUE;
    }

    @Override
    public Page<GetLoginLogListResponseDTO> getLoginLogList(GetLoginLogListRequestDTO getLoginLogListRequestDTO) {
        QueryWrapper<SmilePlusLoginLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (ObjectUtil.isNotNull(getLoginLogListRequestDTO)) {
            if (StrUtil.isNotBlank(getLoginLogListRequestDTO.getUserName())){
                queryWrapper.eq("user_name", getLoginLogListRequestDTO.getUserName());
            }
            if (ObjectUtil.isNotNull(getLoginLogListRequestDTO.getStartTime())&&ObjectUtil.isNotNull(getLoginLogListRequestDTO.getEndTime())){
                queryWrapper.between("create_time", getLoginLogListRequestDTO.getStartTime(), getLoginLogListRequestDTO.getEndTime());
            }
        }

        Page<SmilePlusLoginLog> smilePlusLoginLogPage = loginLogMapper.selectPage(new Page<>(getLoginLogListRequestDTO.getCurrentPage(), getLoginLogListRequestDTO.getPageSize()), queryWrapper);

        return MyBatisPlusPageConverter.convertPage(smilePlusLoginLogPage, GetLoginLogListResponseDTO.class);
    }
}
